package com.fang.networkdisk.handler;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import com.fang.common.common.CommonConstants;
import com.fang.common.exception.ExceptionCode;
import com.fang.common.util.CommonResultUtil;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description Sentinel限流全局统一处理
 * @Author Bernie_fang
 * @Date 2025/4/7 22:38
 **/
@Component
public class SentinelBlockExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
//        response.setStatus(HttpStatus.TOO_MANY_REQUESTS.value());
        response.setStatus(HttpStatus.OK.value());
        String result = JSON.toJSONString(CommonResultUtil.failed(ExceptionCode.CommonCode.SERVER_BUSY));
        response.setCharacterEncoding(CommonConstants.CommonResponse.UTF8);
        response.setContentType(CommonConstants.CommonResponse.APPLICATION_JSON_U8);
        response.getWriter().write(result);
    }
}
